package com.pybox.service;

import com.pybox.common.utils.DateUtils;
import com.pybox.common.utils.JdbcTemplateUtils;
import com.pybox.common.utils.ParamUtils;
import com.pybox.dto.*;
import com.pybox.entity.TUsers;
import com.pybox.oauth.conf.UserDto;
import com.pybox.repository.TCabinetUsersRepository;
import com.pybox.repository.TUserGroupObjectsRepository;
import com.pybox.repository.TUsersRepository;
import com.pybox.spec.TUsersSpec;
import com.pybox.util.HttpSessionUtil;
import com.pybox.util.UserUtils;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 描述：TUsers Service
 *
 * @author wuyingkai
 * @date 2018-09-15
 */

@Service
@Transactional
public class TUsersService {

    @Autowired
    private TUsersRepository repository;

    @Autowired
    private TUserGroupObjectsRepository tUserGroupObjectsRepository;

    @Autowired
    private TCabinetUsersRepository tCabinetUsersRepository;

    @Autowired
    private TCabinetUsersService tCabinetUsersService;
    @Autowired
    private JdbcTemplateUtils jdbcTemplateUtils;

    /**
     * 创建TUsers
     *
     * @param source
     * @return
     */
    public boolean create(TUsersDto source) {
        TUsers target = new TUsers();
        //需要修改创建人 中文
        BeanUtils.copyProperties(source, target);
        target.setDeleted(0);
        target.setState(0);
        target.setCtime(new Timestamp(DateUtils.getNowDate().getTime()));
        target.setUtime(new Timestamp(DateUtils.getNowDate().getTime()));
        //添加管理员同客户
        Integer userId = UserUtils.getCurrentUser().getId();
        if (userId != null || userId > 0) {
            target.setCreateBy(userId.toString());
        }
        Integer cId = UserUtils.getCurrentUser().getCustomerId();

        if (cId != null && cId > 0) {
            target.setCustomerId(cId);
        }
        repository.save(target);

        //当新增是管理员的时候要存管理的柜子权限
        if (source.getCabinetsId() != null && source.getCabinetsId().size() > 0) {
            TCabinetUsersDto tCabinetUsersDto = new TCabinetUsersDto();
            for (Integer id : source.getCabinetsId()) {
                tCabinetUsersService.updateAllCabinet(id);
                tCabinetUsersDto.setDeleted(0);
                tCabinetUsersDto.setCabinetId(id);
                tCabinetUsersDto.setUserId(target.getId());
                tCabinetUsersDto.setCtime(new Timestamp(DateUtils.getNowDate().getTime()));
                tCabinetUsersService.create(tCabinetUsersDto);
            }
        }
        return true;

    }

    /**
     * 根据ID删除TUsers
     *
     * @param id
     * @return
     */
    public boolean delete(Integer id) {
        //逻辑删除
        TUsers exist = repository.findOne(id);
        exist.setDeleted(1);
        repository.save(exist);
        return true;

    }

    /**
     * 更新TUsers
     *
     * @param id
     * @param source
     * @return
     */
    public boolean update(Integer id, TUsersDto source) {

        TUsers exist = repository.findOne(id);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }
        if (exist.getIsAdmin() != 2) {   //表示是管理员
            BeanUtils.copyProperties(source, exist, new String[]{"id", "customerId", "state"});
        } else {            //普通的用户存在更新state
            BeanUtils.copyProperties(source, exist, new String[]{"id", "customerId"});
        }
        exist.setUtime(new Timestamp(DateUtils.getNowDate().getTime()));
        exist.setDeleted(0);
        exist.setUpdateBy(UserUtils.getUserId().toString());
        repository.save(exist);

        //当新增是管理员的时候要存管理的柜子权限
        if (source.getCabinetsId() != null && source.getCabinetsId().size() > 0) {
            TCabinetUsersDto tCabinetUsersDto = new TCabinetUsersDto();
            for (Integer cid : source.getCabinetsId()) {

                tCabinetUsersDto.setDeleted(0);
                tCabinetUsersDto.setCabinetId(cid);
                tCabinetUsersDto.setUserId(id);
                tCabinetUsersDto.setCtime(new Timestamp(DateUtils.getNowDate().getTime()));
                tCabinetUsersService.create(tCabinetUsersDto);
            }
        }
        return true;

    }

    /**
     * 根据ID查询TUsers
     *
     * @param id
     * @return
     */
    public TUsersDto detail(Integer id) {

        TUsers exist = repository.findOne(id);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }

        TUsersDto target = new TUsersDto();
        BeanUtils.copyProperties(exist, target);
        target.setCabinetsId(tCabinetUsersRepository.findTCabinetIdByUserId(target.getId()));
        return target;

    }

    /**
     * 根据用户名查询TUsers
     *
     * @param username
     * @return
     */
    public UserDto getLoginUser(String username) {

        TUsers exist = repository.getLoginUser(username);
        if (null == exist) {
            throw new RuntimeException("记录不存在");
        }

        // System.out.println("登录人的客户id"+exist.getCustomerId());
        UserDto target = new UserDto();
        BeanUtils.copyProperties(exist, target);
        Integer customerId = exist.getCustomerId();
        //System.out.println("customerId ======"+ customerId);
        UserDto user = UserUtils.getCurrentUser();
        if (user.getCustomerId() != null && user.getCustomerId() > 0) {
            target.setCustomerId(user.getCustomerId());
        }
        target.setId(exist.getId());
        String permit = exist.getPermission();
        if (!StringUtils.isEmpty(permit)) {
            String[] permits = permit.split(",");
            List<GrantedAuthority> list = new ArrayList<>();
            for (String per : permits) {
                list.add(new SimpleGrantedAuthority(per));
            }
            target.setAuthorities(list);
        }
        return target;

    }


    public Result<Boolean> checkUserNameUnique(String username) {
        boolean exist = false;
        Integer customerId = UserUtils.getCurrentUser().getCustomerId();
        Integer count = repository.checkUserNameUnique(username, customerId);
        if (count > 0) {
            exist = true;
        }
        return Result.ok(exist);
    }

    public Result<Boolean> checkUserPasswordUnique(String password) {
        boolean exist = false;
        Integer customerId = UserUtils.getCurrentUser().getCustomerId();
        Integer count = repository.checkUserPasswordUnique(password, customerId);
        if (count > 0) {
            exist = true;
        }
        return Result.ok(exist);

    }

    /**
     * 分页查询查询TUsers
     *
     * @param pageNo
     * @param pageSize
     * @param paramMap
     * @return
     */
    public Page<TUsersDto> page(Integer pageNo, Integer pageSize, Map<String, String> paramMap) {

        Pageable pageable = new PageRequest(pageNo - 1, pageSize);
        List<Object> object = new ArrayList<>();
        //默认只能看自己一个公司的
        String customerId = UserUtils.getCustomerId().toString();
        paramMap.put("customerId", customerId);

        StringBuffer sql = new StringBuffer("SELECT\n" +
                " u.id," +
                "\tu.username,u.realname,u.phone,u.email,u.ctime,u.utime\n" +
                "FROM\n" +
                "\tt_users u where 1=1");
        StringBuffer where = new ParamUtils().getUserParams(sql, paramMap);

        Page<TUsersDto> data = jdbcTemplateUtils.page(where, object, TUsersDto.class, pageNo, pageSize);

        Page<TUsersDto> page = new PageImpl<>(data.getContent(), pageable, data.getTotalElements());

        return page;

    }

    /**
     * 一个用户关联多个组
     *
     * @param dto
     * @return
     */
    public Result<Boolean> updateGroupIdsByUserId(UserGroupsDto dto) {
        //先删除再插入记录
        tUserGroupObjectsRepository.deleteGroupIdsByUserId(dto.getUserId());
        for (Integer groupId : dto.getGroupIds()) {
            tUserGroupObjectsRepository.addGroupIdByUserId(dto.getUserId(), groupId);
        }
        return Result.ok(true);
    }


    //一个用户关联多个物品
    public Result<Boolean> updateObjectsByUserId(UserObjectsDto dto) {
        //更新关联为空
        tUserGroupObjectsRepository.deleteObjectIdsByUserId(dto.getUserId());
        for (Integer objectId : dto.getObjectIds()) {
            tUserGroupObjectsRepository.addObjectIdsByUserId(dto.getUserId(), objectId);
        }
        return Result.ok(true);
    }

    //根据用户获取用户关联的物品
    public Result<UserObjectsDto> getObjectIdsByUserId(Integer userId) {
        List<Integer> objectsIds = tUserGroupObjectsRepository.getObjectIdsByUserId(userId);
        UserObjectsDto dto = new UserObjectsDto();
        dto.setUserId(userId);
        dto.setObjectIds(objectsIds);
        return Result.ok(dto);
    }

    //查询与用户关联的分组
    public Result<UserGroupsDto> getGroupIdsByUserId(Integer userId) {
        List<Integer> groupIds = tUserGroupObjectsRepository.getGroupIdsByUserId(userId);
        UserGroupsDto dto = new UserGroupsDto();
        dto.setGroupIds(groupIds);
        dto.setUserId(userId);
        return Result.ok(dto);
    }

    //重置密码
    public Result<Boolean> resetPassword(PasswordDto passwordDto) {
        //校验旧密码
        Integer userId = UserUtils.getCurrentUser().getId();
        // System.out.println("userId"+userId);
        if (userId == 0) {
            Result.ok(false);
        }
        Integer count = repository.checkPassword(passwordDto.getOldPassword(), userId);
        if (count > 0) {
            Integer resetCount = repository.resetPassword(passwordDto.getNewPassword(), userId);
            if (resetCount == 0) {
                // System.out.println("重置出错");
                return Result.ok(false);
            } else {
                //  System.out.println("重置成功");
                return Result.ok(true);
            }
        } else {
            //System.out.println("没有找到这个人匹配的旧密码");
            return Result.ok(false);
        }
    }

    //设置管理员
    public Result<Boolean> upDateAdminByUserId(Integer isAdmin, Integer userId) {
        repository.upDateAdminByUserId(isAdmin, userId);
        return Result.ok(true);
    }

    public Result<Boolean> CheckPassword(String password, Integer userId) {
        repository.checkPassword(password, userId);
        return Result.ok(true);
    }

    public Result<List<TUsersDto>> getAllShPeople() {

        List<Object> object = new ArrayList<>();
        //默认只能看自己一个公司的
        String customerId = UserUtils.getCustomerId().toString();

        StringBuffer sql = new StringBuffer("SELECT\n" +
                " u.id," +
                "\t u.realname\n" +
                "FROM\n" +
                "\tt_users u where (u.is_admin =0  or u.is_admin = 1)");
        sql.append("  and u.customer_id = '" + customerId + "'");
        List<TUsersDto> data = jdbcTemplateUtils.list(sql, object, TUsersDto.class);

        return Result.ok(data);
    }
}